import url from 'url';
import router from 'koa-router';
import DBConnectTool from '../com/DBTool/DBConnectTool';
import ContentTypeTool from '../lib/ContentTypeTool';

const DBRoutes = new router({prefix: '/DBService'});

// 通配符的写法
DBRoutes
    .get('/(.*)', async (ctx: any) => {
        let reqUrl = ctx.request.url.replace('/DBService/', '');
        let urlObj = url.parse(reqUrl, true) as any;
        // let query = urlObj.query;
        reqUrl = decodeURI(urlObj.pathname);

        let pathItem = reqUrl.split('/');

        if (pathItem?.length) {
            let DBName = pathItem.shift();
            let fullPath = '/' + pathItem.join('/');

            let file;
            let dbTool = await DBConnectTool.openDB(DBName);

            if (dbTool) {
                file = await dbTool.getFileByFullPath(fullPath, false);
                if (!file || !file.file_data) {
                    ctx.status = 422;
                    ctx.set('Content-Type', 'application/json;charset=utf-8');
                    ctx.body = JSON.stringify({message: `资源库【${DBName}】连接成功，但找不到该文件资源，路径：【${fullPath}】`});
                } else {
                    let contentType = ContentTypeTool.getContentType(file.file_name);
                    file.file_zip === 'gzip' && (ctx.set('Content-Encoding', 'gzip'));
                    ctx.set('Content-Type', contentType);
                    ctx.body = file.file_data;
                }
            } else {
                ctx.status = 422;
                ctx.set('Content-Type', 'application/json;charset=utf-8');
                ctx.body = JSON.stringify({message: `资源库不存在【${DBName}】，请检查 Url`});
                return;
            }
        }
    })
;


export default DBRoutes;
